package example2;

import javax.sound.sampled.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

public class RecordAudio {
    static final String OUT_PATH_NAME = "C:/Users/yangyang/Desktop/" + System.currentTimeMillis() + ".WAVE";

    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
    ByteArrayOutputStream byteStream;

    public RecordAudio() throws LineUnavailableException {
        float sampleRate = 16000;
        int sampleSizeInBits = 16;
        int channels = 1;
        boolean signed = true;
        boolean bigEndian = false;
        audioFormat = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
        targetDataLine = AudioSystem.getTargetDataLine(audioFormat);
        byteStream = new ByteArrayOutputStream();
    }

    public void start() throws Exception {
        targetDataLine.open(audioFormat);
        targetDataLine.start();

        //声音录入的权值
        int weight = 2;
        //判断是否停止的计数
        int downSum = 0;

        int flag = 0;
        byte[] bytes = new byte[256];
        while ((flag = targetDataLine.read(bytes, 0, bytes.length)) > 0) {
            //当数组末位大于weight时开始存储字节（有声音传入），一旦开始不再需要判断末位
            if (Math.abs(bytes[bytes.length - 1]) > weight || byteStream.size() > 0) {
                byteStream.write(bytes);
                System.out.println("守卫：" + bytes[0] + ",末尾：" + bytes[bytes.length - 1] + ",lenght" + bytes.length);
                //判断语音是否停止
                if (Math.abs(bytes[bytes.length - 1]) <= weight) {
                    downSum++;
                } else {
                    System.out.println("重置奇数");
                    downSum = 0;
                } //计数超过20说明此段时间没有声音传入(值也可更改)
                if (downSum > 200) {
                    System.out.println("停止录入");
                    break;
                }
            }
        }//
    }

    public void stop() throws Exception {
        System.out.println("停止录制");
        byte[] byteArray = byteStream.toByteArray();
        ByteArrayInputStream stream = new ByteArrayInputStream(byteArray);
        long length = byteArray.length / audioFormat.getFrameSize();
        AudioInputStream inputStream = new AudioInputStream(stream, audioFormat, length);
        AudioSystem.write(inputStream, AudioFileFormat.Type.WAVE, new File(OUT_PATH_NAME));
        //
        targetDataLine.stop();
        targetDataLine.close();
    }
}
